package com.example.shop.service.impl;

import com.example.shop.entity.LoginInfo;
import com.example.shop.entity.User;
import com.example.shop.dao.UserMapper;
import com.example.shop.service.UserService;
import com.example.shop.util.JwtUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2025-03-26 09:28:47
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param userid 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer userid) {
        return this.userMapper.queryById(userid);
    }


    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userMapper.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userMapper.update(user);
        return this.queryById(user.getUserid());
    }

    /**
     * 通过主键删除数据
     *
     * @param userid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userid) {
        return this.userMapper.deleteById(userid) > 0;
    }

    @Override
    public boolean register(User user) {
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            return false; // 用户名已存在
        }
        userMapper.insert(user);
        return true; // 注册成功
    }

    @Override
    public LoginInfo login(String username, String password) {
        User user = userMapper.selectByUsername(username);

        Map<String, Object> claims = new HashMap<>();

        if (user != null && user.getPassword().equals(password)) {
            //生成令牌
            claims.put("userid", user.getUserid());
            claims.put("name", user.getName());
            String s = JwtUtils.generateJwt(claims);

            return new LoginInfo(user.getUserid(), user.getName(), s); // 登录成功
        }
        return null; // 登录失败
    }

    @Override
    public User queryByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public boolean register(String username, String password, String email) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        return userMapper.insert(user) > 0;
    }

}
